//
//  PaperToolView.m
//  ZYOnlineSchool
//
//  Created by 毕武侠 on 2017/2/24.
//  Copyright © 2017年 bwx. All rights reserved.
//

#import "PaperToolView.h"
#import "PaperSliderView.h"
#import "PaperModuleTitleView.h"
#import "PagerTitleView.h"

#import <Masonry/Masonry.h>

@interface PaperToolView () <didSelectDelegate>

@property (nonatomic, strong) UIButton *backBtn;        // 返回按钮
@property (nonatomic, strong) UIButton *restBtn;        // 休息一下按钮
@property (nonatomic, strong) UIButton *penBtn;         // 笔按钮
@property (nonatomic, strong) UIButton *cardBtn;        // 答题卡按钮
@property (nonatomic, strong) UIButton *pointBtn;       // 点按钮
@property (nonatomic, strong) PaperSliderView *sliderView; // 滑动条
@property (nonatomic, strong) PaperModuleTitleView *moduleTitleView;

@property (nonatomic, strong) PagerTitleView* titleView;

@property (nonatomic, strong) RACSubject *moduleSelectSignal;    // 模块选择Signal

/** 答题花费的时间数值 */
@property (nonatomic, strong) UILabel  *timerLabel;      // 时间
@property (nonatomic, strong) UILabel  *titleLabel;      // 标题
@property (nonatomic, strong) NSTimer  *timer;           // 答题计时器
@property (nonatomic, assign) CGFloat btnleft;

@end

@implementation PaperToolView

-(PagerTitleView *)titleView
{
    if (!_titleView) {
        _titleView = [PagerTitleView new];
        _titleView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_titleView];
        
        [_titleView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(@0);
            make.height.equalTo(@44);
            make.top.equalTo(@kNavigationBarHeight);
        }];
    }
    return _titleView;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupConfigureView];
    }
    return self;
}

- (void)setupConfigureView {
    self.backgroundColor = MainThemeColor;
    self.moduleSelectSignal = [RACSubject subject];
    
    self.titleLabel.hidden = YES;
    [self addSubview:self.titleLabel];
    
    self.backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, kStatusBarHeight, 44, 44)];
    [self.backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [self addSubview:self.backBtn];
    self.btnleft = SCREEN_WIDTH - 48;
    
    [self addSubview:self.restBtn];
    self.restSignal = [RACSubject subject];
    
    

}
- (UIButton *)restBtn{
    if (!_restBtn) {
        _restBtn = [[UIButton alloc] init];
        [_restBtn addTarget:self action:@selector(restBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _restBtn;
}
- (void)restBtnAction:(UIButton *)btn{
    [self.restSignal sendNext:btn];
}

- (void)setShowToolTimer:(BOOL)showToolTimer {
    _showToolTimer = showToolTimer;
    if (showToolTimer == YES) {
        self.timerLabel = [[UILabel alloc] initWithFrame:CGRectMake(44, kStatusBarHeight, 94, 44)];
        self.timerLabel.textColor = [UIColor whiteColor];
        self.timerLabel.text = @"00 : 00";
        [self addSubview:self.timerLabel];
        
        //self.restBtn = [[UIButton alloc] initWithFrame:self.timerLabel.frame];
        self.restBtn.frame = self.timerLabel.frame;
    }
}
#pragma mark ---------纠错、收藏、分享-----------
- (void)setShowToolMore:(BOOL)showToolMore {
    _showToolMore = showToolMore;
    if (showToolMore == YES) {
        self.pointBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.btnleft, kStatusBarHeight, 44, 44)];
        [self.pointBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [self addSubview:self.pointBtn];
        self.btnleft = SCREEN_WIDTH - 96;
    }
}

//- (void)setShowToolCard:(BOOL)showToolCard {
//    _showToolCard = showToolCard;
//    if (showToolCard == YES) {
//        self.cardBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.btnleft, kStatusBarHeight, 44, 44)];
//        [self.cardBtn setImage:[UIImage imageNamed:@"TiPageImage"] forState:UIControlStateNormal];
//        [self addSubview:self.cardBtn];
//        self.btnleft = SCREEN_WIDTH - 144;
//    }
//}

- (void)setShowToolPen:(BOOL)showToolPen {
    _showToolPen = showToolPen;
    if (showToolPen == YES) {
        self.penBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.btnleft, kStatusBarHeight, 44, 44)];
        [self.penBtn setImage:[UIImage imageNamed:@"TiPenImage"] forState:UIControlStateNormal];
        [self addSubview:self.penBtn];
        
        self.btnleft = SCREEN_WIDTH - 194;
    }
}

- (void)setShowToolSliderView:(BOOL)showToolSliderView {
    _showToolSliderView = showToolSliderView;
    if (_showToolSliderView == YES) {
        self.sliderView = [[PaperSliderView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, SCREEN_WIDTH, 40)];
        [self addSubview:self.sliderView];
    }
}

- (void)setShowToolModuleTitleView:(BOOL)showToolModuleTitleView {
    _showToolModuleTitleView = showToolModuleTitleView;
    if (_showToolModuleTitleView == YES) {
        self.moduleTitleView = [[PaperModuleTitleView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, SCREEN_WIDTH, 40)];
        self.moduleTitleView.selectDelegate = self;
        [self addSubview:self.moduleTitleView];
    }
}

- (void)setNum:(NSUInteger)num withCount:(NSUInteger)count {
    
    NSString *str = [NSString stringWithFormat:@"%ld/%ld", num, count];

#if TGT_XBGK
    self.titleView.titleLabel.text = self.title;
    self.titleView.countLabel.text = str;
#warning  王旭修改 #elif 缺少条件
#else
    self.sliderView.title = str;
#endif
    self.sliderView.progress = count == 0 ? 0 : (CGFloat)num / count;
}

- (void)setCurrentModuleAtIndex:(NSUInteger)index {
    self.moduleTitleView.index = index;
}

- (void)setTitle:(NSString *)title {
    _title = title;
    
#if TGT_XBGK
    self.titleLabel.hidden = YES;
#warning  王旭修改 #elif 缺少条件
#else
    self.titleLabel.text = title;
    self.titleLabel.hidden = NO;
#endif

}

- (void)setModules:(NSMutableArray *)modules {
    _modules = modules;
    self.moduleTitleView.datas = modules;
}

#pragma mark time action
/** 开始计时⌛️ */
- (void)startTimer {
    if (self.showToolTimer == NO) {
        return;
    }
    
    if (self.timer) {
        [self endTimer];
    }
    
    self.startDate = [NSDate date];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(clockingAsc) userInfo:nil repeats:YES];
}

/** 结束计时⌛️ */
- (void)endTimer {
    [self.timer invalidate];
    self.timer = nil;
}

/** 暂停计时⌛️*/
- (void)pauseTimer {
    [self.timer setFireDate:[NSDate distantFuture]];
}

/** 恢复计时⌛️*/
- (void)restartTimer {
    [self.timer setFireDate:[NSDate distantPast]];
}

// 正计时⌛️
- (void)clockingAsc {
    self.duration++;
    if (self.surplus != 0 && self.duration == self.surplus) {       // 到达最大时间
        [self pauseTimer];
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SENDPAPER object:nil];
    }
    self.timerLabel.text = [self TimeformatFromSeconds:self.duration];
}

#pragma mark - ViewSignalProtocol

- (RACSignal *)getSignalWithDictionary:(NSDictionary *)dict {
    NSString *str = dict[@"action"];
    if (!str)   return [RACSignal empty];
    
    if ([str isEqualToString:@"back"]) {     // 画板
        return [self.backBtn rac_signalForControlEvents:UIControlEventTouchUpInside];
    } else if ([str isEqualToString:@"rest"]) {     // 画板
        return [self.restBtn rac_signalForControlEvents:UIControlEventTouchUpInside];
    } else if ([str isEqualToString:@"pen"]) {     // 画板
        return [self.penBtn rac_signalForControlEvents:UIControlEventTouchUpInside];
    } else if ([str isEqualToString:@"card"]) {
        return [[self.cardBtn rac_signalForControlEvents:UIControlEventTouchUpInside] map:^id(id value) {
            return [NSNumber numberWithUnsignedInteger:self.duration];
        }];
    } else if ([str isEqualToString:@"more"]) {
        return [self.pointBtn rac_signalForControlEvents:UIControlEventTouchUpInside];
    } else if ([str isEqualToString:@"module"]) {
        return self.moduleSelectSignal;
    } else {
        return [RACSignal empty];
    }
}

#pragma mark - 工具方法
/** 秒数转换成 时 分 秒 */
- (NSString *)TimeformatFromSeconds:(NSInteger)seconds {
    // format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02d", (int)(seconds / 3600)];
    // format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02d", (int)((seconds % 3600) / 60)];
    // format of second
    NSString *str_second = [NSString stringWithFormat:@"%02d", (int)(seconds % 60)];
    // format of time
    NSString *format_time = [NSString stringWithFormat:@"%@ : %@ : %@", str_hour, str_minute, str_second];
    if ((int)(seconds / 3600) == 0) { // 如果小时数值为0，不显示小时
        format_time = [NSString stringWithFormat:@"%@ : %@", str_minute, str_second];
    }
    return format_time;
}

// 显示只有计数器模式
- (void)showTimerType {
    if (self.type == PaperToolTypeTimer) return;
    
    self.type = PaperToolTypeTimer;
//    self.sliderView.alpha = 1.0;
    self.sliderView.alpha = self.showToolModuleTitleView == YES ? 0.0 :1.0;
    self.moduleTitleView.alpha = self.showToolModuleTitleView == YES ? 1.0 :0.0;
    
    [UIView animateWithDuration:0.4 animations:^{
        self.timerLabel.textAlignment = NSTextAlignmentCenter;
        self.timerLabel.left = SCREEN_WIDTH / 2 - 50;
        self.penBtn.alpha = 0.0;
        self.cardBtn.alpha = 0.0;
        
        self.pointBtn.alpha = 0.0;
        self.pointBtn.enabled = NO;

//        self.moduleTitleView.alpha = 0.0;
    }];
}

// 显示正常模式
- (void)showNormalType {
    if (self.type == PaperToolTypeNormal) return;
    
    self.type = PaperToolTypeNormal;
    self.sliderView.alpha = self.showToolModuleTitleView == YES ? 0.0 :1.0;
    self.moduleTitleView.alpha = self.showToolModuleTitleView == YES ? 1.0 :0.0;
    [UIView animateWithDuration:0.4 animations:^{
        self.timerLabel.textAlignment = NSTextAlignmentLeft;
        self.timerLabel.left = 50;
        self.penBtn.alpha = 1.0;
        self.cardBtn.alpha = 1.0;
        
        self.pointBtn.alpha = 1.0f;
        self.pointBtn.enabled = YES;
    }];
}

// 显示模块介绍页
- (void)showModuleType {
    if (self.type == PaperToolTypeModule) return;
    
    self.type = PaperToolTypeModule;
    self.moduleTitleView.alpha = 1.0;
    self.sliderView.alpha = 0.0;
    
    [UIView animateWithDuration:0.4 animations:^{
        self.penBtn.alpha = 1.0;
        self.pointBtn.alpha = 1.0f;
        self.pointBtn.enabled = NO;
    }];
}

#pragma mark - didSelectDelegate

- (void)didSelectAtIndex:(NSInteger)index {
    [self.moduleSelectSignal sendNext:[NSIndexPath indexPathForRow:0 inSection:index]];
}

#pragma mark - getter

- (UILabel *)titleLabel {
    if (_titleLabel == nil) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 50, kStatusBarHeight, 100, 44)];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = [UIColor whiteColor];
    }
    return _titleLabel;
}
- (void)dealloc{
    self.duration = 0;
    [self.timer invalidate];
    self.surplus = 0;
    self.startDate = nil;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
